package com.suian.spring.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class T4ThreadPoolExecutor {
    public static void main(String[] args) {
        AtomicInteger flag = new AtomicInteger(1);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                3,
                5,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>()
        );

//        executor.execute(()->{
//            while (true) {
//                System.out.println("TaskName: "+Thread.currentThread().getName()+" 运行了 "+(flag.getAndIncrement())+"次");
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        });
//
//        executor.execute(()->{
//            while (true) {
//                System.out.println("TaskName: "+Thread.currentThread().getName()+" 运行了 "+(flag.getAndIncrement())+"次");
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        });

        //模拟阻塞
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executor.submit(() -> {
                try {
                    System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName());
                    // 模拟任务执行时间
                    Thread.sleep(10000);
                    System.out.println("Task " + taskId + " is completed.");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        //关闭线程池
        executor.shutdown();
    }
}
